﻿using System;
using System.Web;
using FBGraph.Configuration;
using FBGraph.Web.Configuration;

namespace FBGraph.Web.Security
{
    /// <summary>An implementation of <see cref="IHttpModule" /> that provides FBGraph.NET authorization functionality for WebForms applications.</summary>
    public class FBGraphAuthorizationModule : IHttpModule, IFBGraphAuthorizationHandler, IFBGraphAuthorizationResultHandler
    {
        void IHttpModule.Init(HttpApplication context)
        {
            context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);
        }

        void context_AuthorizeRequest(Object sender, EventArgs e)
        {
            var config = new FBGraphConfigurationManager();
            var authConfig = config.GetAuthorizationConfiguration();
            if (authConfig != null)
            {
                var app = (HttpApplication)sender;
                var httpContext = new HttpContextWrapper(app.Context);
                var scope = authConfig.GetExtendedPermissions();

                if (authConfig.AppAuthorization.IsRequired && !this.Authorize(httpContext, scope))
                {
                    this.ExecuteAuthorizationRedirect(httpContext, scope);
                }
            }
        }

        void IHttpModule.Dispose() { }
    }
}